package io.github.yidasanqian.bean;

import org.dozer.DozerBeanMapperBuilder;
import org.dozer.Mapper;
import org.dozer.loader.api.BeanMappingBuilder;
import org.dozer.loader.api.FieldsMappingOptions;
import org.dozer.loader.api.TypeMappingBuilder;

/**
 * @author Linyu Chen
 */
public class DozerBeanMappingBuilder extends BeanMappingBuilder {

    private Class<?> source;
    private Class<?> destination;
    private String[] srcFields;
    private String[] destFields;
    private String[] excludeFields;

    public DozerBeanMappingBuilder(Class<?> source, Class<?> destination, String[] srcFields, String[] destFields, String[] excludeFields) {
        this.source = source;
        this.destination = destination;
        this.srcFields = srcFields;
        this.destFields = destFields;
        this.excludeFields = excludeFields;
    }

    public DozerBeanMappingBuilder(Class<?> source, Class<?> destination, String[] excludeFields) {
        this(source, destination, null, null, excludeFields);
    }

    public DozerBeanMappingBuilder(Class<?> source, Class<?> destination) {
        this(source, destination, null, null, null);
    }


    @Override
    protected void configure() {
        TypeMappingBuilder mappingBuilder = mapping(source, destination);
        if (srcFields != null) {
            if (srcFields.length == destFields.length) {
                for (int i = 0; i < srcFields.length; i++) {
                    mappingBuilder.fields(srcFields[i], destFields[i], FieldsMappingOptions.copyByReference());
                }
            } else {
                throw new RuntimeException("srcFields length != destFields length");
            }
        }
        if (excludeFields != null) {
            for (int i = 0; i < excludeFields.length; i++) {
                mappingBuilder.exclude(excludeFields[i]);
            }
        }
    }

    public Mapper getDozerMapper() {
        return DozerBeanMapperBuilder.create()
                .withMappingBuilder(this)
                .build();
    }
}
